package com.lhfeiyu.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Assets;
import com.lhfeiyu.config.Const;
import com.lhfeiyu.config.Tip;
import com.lhfeiyu.config.base.BaseTip;
import com.lhfeiyu.dao.WxMsgCountMapper;
import com.lhfeiyu.dao.base.BaseFansMapper;
import com.lhfeiyu.dao.base.BaseGoodsMapper;
import com.lhfeiyu.po.WxMsgCount;
import com.lhfeiyu.po.base.BaseFans;
import com.lhfeiyu.po.base.BaseGoods;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.service.base.CommonService;
import com.lhfeiyu.thirdparty.wx.business.MessageNews;
import com.lhfeiyu.thirdparty.wx.business.New;
import com.lhfeiyu.thirdparty.wx.business.News;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;

@Service
public class WxMsgCountService extends CommonService<WxMsgCount>{
	
	@Autowired
	WxMsgCountMapper wxMsgCountMapper;
	@Autowired
	BaseFansMapper fansMapper;
	@Autowired
	BaseGoodsMapper goodsMapper;
	
	public JSONObject getWxMsgCountList(JSONObject json, Map<String, Object> map) {
		List<WxMsgCount> wxMsgCountList = wxMsgCountMapper.selectListByCondition(map);
		Integer total = wxMsgCountMapper.selectCountByCondition(map);
		return Result.gridData(wxMsgCountList, total, json);
	}
	
	/**
	 * 新增或修改微信消息数量
	 * @param json 消息数据容器对象（主要用于保存提示消息或数据）
	 * @param wxMsgCount 微信消息数量对象
	 * @param username 操作人名称（数据库记录）
	 * @return JSONObject
	 */
	public JSONObject addUpdateWxMsgCount(JSONObject json, WxMsgCount wxMsgCount, String username){
		if(null == wxMsgCount.getId()){//添加
			return addWxMsgCount(json, wxMsgCount, username);
		}else{//修改
			return updateWxMsgCount(json, wxMsgCount, username);
		}
	}
	
	/**
	 * 新增微信消息数量（代码若已经存在则提示失败）
	 * @param json 消息数据容器对象（主要用于保存提示消息或数据）
	 * @param wxMsgCount 微信消息数量对象
	 * @param username 操作人名称（数据库记录）
	 * @return JSONObject
	 */
	public JSONObject addWxMsgCount(JSONObject json, WxMsgCount wxMsgCount, String username){
		Date date = new Date();
		wxMsgCount.setId(null);
		wxMsgCount.setSerial(CommonGenerator.getSerialByDate(Assets.serial_prefix_wxMsgCount));
		wxMsgCount.setMainStatus(1);
		wxMsgCount.setCreatedBy(username);
		wxMsgCount.setCreatedAt(date);
		wxMsgCountMapper.insert(wxMsgCount);
		json.put("wxMsgCountId", wxMsgCount.getId());
		return Result.success(json);
	}
	
	/**
	 * 修改微信消息数量（ID不能为空，数据库中必须存在该ID的数据）
	 * @param json 消息数据容器对象（主要用于保存提示消息或数据）
	 * @param wxMsgCount 微信消息数量对象
	 * @param username 操作人名称（数据库记录）
	 * @return JSONObject
	 */
	public JSONObject updateWxMsgCount(JSONObject json, WxMsgCount wxMsgCount, String username){
		Date date = new Date();
		Integer wxMsgCountId = wxMsgCount.getId();
		if(null == wxMsgCountId){//添加
			return Result.failure(json, BaseTip.msg_update_id_null, BaseTip.code_update_id_null);
		}
		WxMsgCount dbWxMsgCount = wxMsgCountMapper.selectByPrimaryKey(wxMsgCountId);
		if(null == dbWxMsgCount){
			return Result.failure(json, BaseTip.msg_update_obj_null, BaseTip.code_update_obj_null);
		}
		wxMsgCount.setUpdatedBy(username);
		wxMsgCount.setUpdatedAt(date);
		wxMsgCountMapper.updateByPrimaryKeySelective(wxMsgCount);
		return Result.success(json);
	}
	
	public JSONObject addOrUpdateWxMsgCount(JSONObject json, BaseUser sessionUser, WxMsgCount wxMsgCount){
			Integer userId = sessionUser.getId();
			String username = sessionUser.getUsername();
			//String serial = sessionUser.getSerial();
			Date date = new Date();
			Map<String,Object> map = CommonGenerator.getHashMap();
			map.put("userId", userId);
			int fansCount = fansMapper.selectCountByCondition(map);
			if(fansCount <= 0){
				return Result.failure(json, Tip.msg_wx_batch_fans_zero, Tip.code_wx_batch_fans_zero);
			}
			int goodsCount = goodsMapper.selectCountByCondition(map);
			String goodsIds = wxMsgCount.getGoodsIds();
			if(goodsCount <= 0){
				return Result.failure(json, Tip.msg_wx_batch_goods_zero, Tip.code_wx_batch_goods_zero);
			}
			if(null == wxMsgCount.getId()){//添加
				wxMsgCount.setUserId(userId);
				wxMsgCount.setMsgType(1);
				wxMsgCount.setCount(0);
				wxMsgCount.setMaxCount(3);
				wxMsgCount.setCreatedBy(username);
				wxMsgCount.setCreatedAt(date);
				wxMsgCount.setSendDate(date);
				wxMsgCountMapper.insert(wxMsgCount);
			}else{//修改
				Integer wxMsgCountId = wxMsgCount.getId();
				WxMsgCount db_wxMsgCount = wxMsgCountMapper.selectByPrimaryKey(wxMsgCountId);
				if(null != db_wxMsgCount){
					if(db_wxMsgCount.getCount() < 3 && db_wxMsgCount.getCount() >= 0){
						Integer count = db_wxMsgCount.getCount();
						Integer maxCount = db_wxMsgCount.getMaxCount();
						wxMsgCount.setCount(++count);
						wxMsgCount.setMaxCount(--maxCount);
					}else{
						json.put("status", "failure");
						json.put("msg", "每天最多只能发3次群发信息");
						return json;
					}
				}
				wxMsgCount.setSendDate(date);
				wxMsgCount.setUpdatedBy(username);
				wxMsgCount.setUpdatedAt(date);
				wxMsgCountMapper.updateByPrimaryKeySelective(wxMsgCount);
			}
			json.put("status", "success");
			json.put("id", wxMsgCount.getId());
			json.put("msg", "操作成功");
			
			sendWxPicMsg(json, userId, goodsIds);
			
		return json;
	}

	public JSONObject sendWxPicMsg(JSONObject json, Integer userId, String goodsIds){
		if(Check.isNull(goodsIds) || Check.isNull(userId)){
			return json;
		}
		Map<String,Object> map = CommonGenerator.getHashMap();
		map.put("goodsIds", goodsIds);
		int fansCount = fansMapper.selectCountByCondition(map);
		if(fansCount <= 0){
			return Result.failure(json, Tip.msg_wx_batch_fans_zero, Tip.code_wx_batch_fans_zero);
		}
		//int goodsCount = goodsMapper.selectCountByCondition(map);
		//String goodsIds = wxMsgCount.getGoodsIds();
		List<BaseGoods> goodsList = goodsMapper.selectListByCondition(map);
		map.clear();
		map.put("userId", userId);
		List<BaseFans> fansList = fansMapper.selectListByCondition(map);
		if(Check.isNull(goodsList) || Check.isNull(fansList)){
			
		}
		MessageNews mn = new MessageNews();
		mn.setMsgtype("news");
		News news = new News();
		List<New> articles = new ArrayList<New>();
		for(BaseGoods g : goodsList){
			New n = new New();
			String description = g.getGoodsDescription();
			String picUrl = Const.web_base_url + g.getPicPath();
			String title = g.getGoodsName();
			///goods/1?shopId=8&r=u201601910214097
			String url = Const.web_base_url+"/goods/"+g.getId()+"?shopId="+g.getShopId();
			if(Check.isNull(description)){
				n.setDescription(BaseTip.msg_goods_description_null);
			}else{
			}
			n.setDescription(description);
			n.setPicurl(picUrl);
			n.setTitle(title);
			n.setUrl(url);
			articles.add(n);
		}
		news.setArticles(articles);
		mn.setNews(news);
		for(BaseFans f : fansList){
			mn.setTouser(f.getWxOpenid());
			com.lhfeiyu.thirdparty.wx.business.Message.sendKFMessage(mn);
		}
		return Result.success(json);
		
	}
	
	
	
}
